var express = require('express');
var router = express.Router();
var { query } = require('../../utils/db')
//栏目列表页
router.get('/list',(req,res)=>{
    var sql = 'select * from category'
    query(sql,(data)=>{
        res.render('admin/category/list',{categories:data})
    })
})

//栏目添加操作
router.post('/add',(req,res)=>{
    var cname = req.body.cname
    var active = req.body.active ? req.body.active : 0;
    var sql = `insert into category (cname,active) values ('${cname}',${active})`

    query(sql,(data)=>{
        req.flash('success','添加成功')
        res.redirect('/admin/category/list')
    })
    
})
//栏目编辑
router.get('/edit',(req,res)=>{
    var cid = req.query.cid
    var sql = `select * from category where cid=${cid}`
    query(sql,(data)=>{
        var category = data[0]
        console.log(category)
        res.render('admin/category/edit.ejs',{category:category})
    })

})
// 编辑栏目保存
router.post('/edit',(req,res)=>{
    console.log(req.body)
    var cname = req.body.cname
    var active = req.body.active ? 1 : 0
    var cid = req.body.cid
    var sql = `update category set cname='${cname}',active=${active} where cid=${cid}`
    query(sql,(data)=>{
        req.flash('success','栏目编辑成功')
        res.redirect('/admin/category/list')
    })
})


module.exports = router;